package at.fhj.itm10.ticketmaster.services.impl;

import java.util.List;

import org.apache.log4j.Logger;

import at.fhj.itm10.ticketmaster.dao.DAOException;
import at.fhj.itm10.ticketmaster.dao.TicketDAO;
import at.fhj.itm10.ticketmaster.entities.Ticket;
import at.fhj.itm10.ticketmaster.helper.Validator;
import at.fhj.itm10.ticketmaster.services.ServiceException;
import at.fhj.itm10.ticketmaster.services.TicketService;

/**
 * {@inheritDoc}
 * 
 * @author Kevin Reinmueller
 */
public class TicketServiceImpl extends AbstractService implements TicketService {

	private Logger logger = Logger.getLogger(TicketServiceImpl.class);
	private TicketDAO dao;

	public TicketDAO getDao() {
		return dao;
	}
	
	public void setDao(TicketDAO ticketDAO) {
		this.dao = ticketDAO;
	}

	public void insertTicket(Ticket ticket) {
		logger.debug("insertTicket()");

		Validator.notNullOrThrow(ticket, "ticket is null");
		Validator.zeroOrThrow(ticket.getId(), "id for new ticket must be zero - will be autofilled");

		try {
			begin();
			getDao().insert(ticket);
			commit();
		} catch (DAOException e) {
			rollback();

			throw new ServiceException("Error on inserting data", e);
		} finally {
			closeConnection();
		}
	}

	public void updateTicket(Ticket ticket) {
		logger.debug("updateTicket()");
		
		Validator.notNullOrThrow(ticket, "ticket is null");
		Validator.notZeroOrThrow(ticket.getId(), "id must be given for update");
		
		try {
			begin();
			getDao().update(ticket);
			commit();
		} catch (DAOException e) {
			rollback();

			throw new ServiceException("Error on updating data", e);
		} finally {
			closeConnection();
		}
	}

	public void deleteTicket(Ticket ticket) {
		logger.debug("deleteOrder()");
		
		Validator.notNullOrThrow(ticket, "ticket is null");
		Validator.notZeroOrThrow(ticket.getId(), "id must be given for delete");

		try {
			begin();
			getDao().delete(ticket);
			commit();
		} catch (DAOException e) {
			rollback();

			throw new ServiceException("Error on deleting data", e);
		} finally {
			closeConnection();
		}
	}

	public Ticket findById(long id) {
		logger.debug("findById()");

		Ticket ticket = null;
		try {
			begin();
			ticket = getDao().findById(id);
			commit();
		} catch (DAOException e) {
			rollback();

			throw new ServiceException("Error on retrieving data", e);
		} finally {
			closeConnection();
		}
		
		return ticket;
	}

	public List<Ticket> findAll() {
		logger.debug("findAll()");

		List<Ticket> tickets = null;
		try {
			begin();
			tickets = getDao().findAll();
			commit();
		} catch (DAOException e) {
			rollback();

			throw new ServiceException("Error on retrieving data", e);
		} finally {
			closeConnection();
		}
		
		return tickets;
	}
}
